﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Web.Routing;

namespace ERPStore.Web.Html
{
	public static class FormatExtensions
	{
		private static System.Globalization.CultureInfo m_Ci
			= new System.Globalization.CultureInfo("en-US");

		public static string ToCurrency(this decimal value)
		{
			return value.ToCurrency(false);
		}

		public static string ToCurrency(this decimal value, bool hideSymbol)
		{
			return System.Web.HttpUtility.HtmlDecode(value.ToCurrencyInternal(hideSymbol));
		}

        public static string ToRawCurrency(this decimal value)
        {
            return value.ToRawCurrency(false);
        }

        public static string ToRawCurrency(this decimal value, bool hideSymbol)
        {
            return value.ToCurrencyInternal(hideSymbol);
        }

		public static string IntegerPart(this ERPStore.Models.Price price)
		{
			var pattern = GetPattern(price.Value);
			var text = price.Value.ToString(pattern, m_Ci);
			var parts = text.Split('.');
			return parts[0].Replace(",", " ");
		}

		public static string IntergerPartWithTax(this ERPStore.Models.Price price)
		{
			var pattern = GetPattern(price.Value);
			var text = price.ValueWithTax.ToString(pattern, m_Ci);
			var parts = text.Split('.');
			return parts[0].Replace(",", " ");
		}

		public static string DecimalPart(this ERPStore.Models.Price price)
		{
			var pattern = GetPattern(price.Value);
			var text = price.Value.ToString(pattern, m_Ci);
			var parts = text.Split('.');
			return parts[1];
		}

		public static string DecimalPartWithTax(this ERPStore.Models.Price price)
		{
			var pattern = GetPattern(price.Value);
			var text = price.ValueWithTax.ToString(pattern, m_Ci);
			var parts = text.Split('.');
			return parts[1];
		}

		internal static string ToCurrencyInternal(this decimal value, bool hideSymbol)
		{
			string symbol = ERPStore.GlobalConfiguration.Configuration.Settings.Format.CurrencySymbol;
			if (hideSymbol)
			{
				symbol = string.Empty;
			}
			var pattern = GetPattern(value);
			return string.Format(pattern, value, symbol);
		}

		internal static string GetPattern(this decimal value)
		{
			var pattern = ERPStore.GlobalConfiguration.Configuration.Settings.Format.NormalPricePattern + "{1}";
			if (value < ERPStore.GlobalConfiguration.Configuration.Settings.Format.SmallPriceLimit)
			{
				pattern = ERPStore.GlobalConfiguration.Configuration.Settings.Format.SmallPricePattern + "{1}";
			}
			return pattern;
		}
	}
}
